package com.lt.flashcard.view;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;

import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.Repository;

public class AdminLoginCtrl extends SelectorComposer<Component> {

	private static final long serialVersionUID = 1L;

	@Wire
	private Textbox username;
	@Wire
	private Textbox password;
	
	public Textbox getUsername() {
		return username;
	}
	
	public void setUsername(Textbox username) {
		this.username = username;
	}
	
	public Textbox getPassword() {
		return password;
	}
	
	public void setPassword(Textbox password) {
		this.password = password;
	}

	
	@Override
	public ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo) {
		AAService srv  = Repository.getInstance().getAAService();
		if(srv.isLogin() && srv.hasRole("admin")) {
			Executions.sendRedirect("/admin.zul");
		}
		return super.doBeforeCompose(page, parent, compInfo);
	}
	
	@Listen("onClick=#btnLogin; onOK=#password; onOK=#username")
	public void doLogin() {
		AAService srv = Repository.getInstance().getAAService();
		try {
			srv.doLogin(username.getValue(), password.getValue(), false, false);
			Executions.sendRedirect("/admin.zul");
		}
		catch (Exception e) {
			Messagebox.show(e.getMessage());
		}
	}
	
}
